import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Block} from '@tarojs/components'
import {AtSearchBar, AtIcon} from 'taro-ui'
import {HotCity, AllCity} from '../../utils/server.interface'
import {location} from '../../utils/location.service'
import {vcmonitor} from "../../utils/tools";
import {http} from '../../utils/http'
import {SEARCH_OUT_CITY, ALL_OUT_CITY} from '../../constants/api'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './city.scss'

interface StateType {
  allCity: AllCity[]
  searchKey: string
  searchCity: HotCity[]
  location: any
  indexStr: string[]
}

type PageOwnProps = {}

type PageState = {}

class SelectCity extends Component {
  state: StateType = {
    allCity: [],
    searchKey: '',
    searchCity: [],
    location: false,
    indexStr: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"]
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    this.setState({location: Taro.getStorageSync('outCity')})
    Taro.showLoading({title: '加载城市中...'})
    const allCity = await http.get<AllCity[]>(ALL_OUT_CITY, {index: 'A'})
    if (allCity) {
      this.setState({allCity})
    }
    Taro.hideLoading()
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async checkWord(index) {
    Taro.showToast({title: index, icon: 'none'})
    const query = Taro.createSelectorQuery();
    query.selectViewport().scrollOffset();
    query.select(`#${index}`).boundingClientRect();
    query.exec(res => {
      Taro.pageScrollTo({
        duration: 300,
        scrollTop: res[0].scrollTop + res[1].top
      })
    })
  }

  async search() {
    const searchCity = await http.get(SEARCH_OUT_CITY, {keywords: this.state.searchKey})
    if (searchCity) {
      this.setState({searchCity})
    }
  }

  inputChange(value) {
    this.setState({searchKey: value})
  }

  hotCityHandle(item, e) {
    location.ignore = true
    e.stopPropagation()
    Taro.setStorageSync('outCity', item)
    this.naviBack()
  }

  indexes(value) {
    const {area_name, region_id} = value
    Taro.setStorageSync('outCity', {area_name, region_id})
    this.naviBack()
  }

  naviBack() {
    Taro.navigateBack({
      delta: 1
    })
  }

  clearSearch() {
    this.setState({searchKey: '', searchCity: []})
  }

  render() {
    const {allCity, searchCity, searchKey, location, indexStr} = this.state
    return (
      <View className='all-city'>
        <GzhAuth />
        <AtSearchBar value={searchKey} onClear={this.clearSearch.bind(this)} onChange={this.inputChange.bind(this)}
          onActionClick={this.search.bind(this)} placeholder='城市名称，如：敖德萨'
        />
        {location && <Block>
          <View className='now-city'>
            <View className='title'>当前选择城市：</View>
            <View className='content'>
              <View className='location' onClick={this.naviBack.bind(this)}><AtIcon value='map-pin'
                size='14'
              /><Text
                className='city-name'
              >{location.area_name}</Text>
              </View>
            </View>
          </View>
        </Block>
        }
        {searchCity.length === 0 && <Block>
          <View className='all-city-index'>
            <View className='text' onClick={() => {
              Taro.pageScrollTo({
                duration: 300,
                scrollTop: 0
              })
            }}
            >TOP</View>
            {indexStr.map(item => <View className='text' key={item}
              onClick={this.checkWord.bind(this, item)}
            >{item}</View>)}
          </View>
          <View className='all-city-box'>
            {allCity.map(item => <View className='city-word' key={item.key}>
              <View className='city-word-title' id={item.key}>{item.title}</View>
              {item.items.map(i => <View className='item' key={i.region_id}
                onClick={this.hotCityHandle.bind(this, i)}
              >{i.area_name}</View>)}
            </View>)}
          </View>
        </Block>}
        {searchCity.length > 0 && searchCity.map(item => <View className='item' key={item.region_id}
          onClick={this.hotCityHandle.bind(this, item)}
        >{item.area_name}</View>)}

      </View>
    )
  }
}

export default SelectCity as ComponentClass<PageOwnProps, PageState>
